package com.example.broadcasttest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private NetworkChangeReceiver ncr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //动态广播
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        ncr = new NetworkChangeReceiver();
        registerReceiver(ncr,intentFilter);
        // 获得按钮触发广播
        Button send = (Button)findViewById(R.id.send_broadcast);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                // 安卓8.0以上，必须给intent指定广播接收者的包名（应用范围）
                intent.addFlags(0x01000000);
                //发送标准广播
//                sendBroadcast(intent);
//                发送有序广播
                sendOrderedBroadcast(intent,null);
            }
        });
    }
    // 注销接收器

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(ncr);
    }

    class NetworkChangeReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo ninfo =  (NetworkInfo)cm.getActiveNetworkInfo();
            if(ninfo != null && ninfo.isAvailable()){
                Toast.makeText(context,"网络已连接！",Toast.LENGTH_SHORT).show();
            }else Toast.makeText(context,"网络已断开！",Toast.LENGTH_SHORT).show();

        }
    }
}